/**
 * Copyright (c) 2011 eelpo.com
 * All rights reserved.
 */
package com.eelpo.cmmp.uac.pages.home;

import com.eelpo.cmmp.basic.services.ISystemConfigManageService;
import com.eelpo.cmmp.core.exception.ServiceException;
import com.eelpo.cmmp.core.wicket.behavior.ComponentVisualErrorBehavior;
import com.eelpo.cmmp.core.wicket.component.label.ErrorLevelsFeedbackMessageFilter;
import com.eelpo.cmmp.core.wicket.page.basic.GuestPage;
import com.eelpo.cmmp.core.wicket.resource.Captcha;
import com.eelpo.cmmp.core.wicket.resource.CaptchaImageResource;
import com.eelpo.cmmp.core.wicket.resource.VerifyExcpetion;
import com.eelpo.cmmp.uac.constants.SystemConfigConstants;
import com.eelpo.cmmp.uac.dao.vo.User;
import com.eelpo.cmmp.uac.services.IPermissionManageService;
import com.eelpo.cmmp.uac.services.IUserManageService;
import com.eelpo.cmmp.uac.session.UACSession;

import org.apache.wicket.Application;
import org.apache.wicket.feedback.FeedbackMessage;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.PasswordTextField;
import org.apache.wicket.markup.html.form.SubmitLink;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.image.NonCachingImage;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.protocol.http.request.WebClientInfo;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * <pre>
 * 
 * 登录页面
 * 
 * </pre>
 * 
 * @author <a href="mailto:Brian@eelpo.com">汪洪州</a>
 * @since 1.0
 */
public class Login extends GuestPage {

	@SpringBean
	protected IUserManageService userManageService;

	@SpringBean
	protected IPermissionManageService permissionManageService;

	@SpringBean
	protected ISystemConfigManageService systemConfigService;

	private static final Logger logger = LoggerFactory.getLogger(Login.class);

	public Login() {

		Captcha captcha = new Captcha();

		Form<User> form = renderForm(captcha);

		renderTitleLabel();
		renderFeedbackPanel(form);
		renderUserAccountTextField(form);
		renderUserPasswordTextField(form);
		renderCaptchaTextField(form, captcha);
		renderLoginLink(form);

		add(form);
	}

	public Form<User> renderForm(final Captcha captcha) {

		User user = new User();

		if (Application.DEVELOPMENT.equalsIgnoreCase(getApplication().getConfigurationType())) {
			try {
				user = userManageService.getSuperManager();
				captcha.setActual("skip");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		return new Form<User>("form", new Model<User>(user)) {
			private static final long serialVersionUID = -7272090635357466950L;

			@Override
			protected void onSubmit() {
				try {

					// 检查验证码
					if (Application.DEPLOYMENT.equalsIgnoreCase(getApplication().getConfigurationType())) {
						captcha.verify();
					}

					// 登录
					User user = (User) getDefaultModelObject();
					String ip = ((WebClientInfo) getRequestCycle().getClientInfo()).getProperties().getRemoteAddress();
					user = userManageService.login(ip, user.getAccount(), user.getPassword());

					// 缓存用户，权限
					UACSession session = UACSession.get();
					session.setUser(user);
					session.setPermissions(permissionManageService.getPermissions(user.getId()));

					// 页面跳转
					setResponsePage(Main.class);
				} catch (VerifyExcpetion e1) {
					info(e1.getMessage());
				} catch (ServiceException e2) {
					info(e2.getMessage());
				} catch (Exception e3) {
					e3.printStackTrace();
					info("用户登录失败！");
				} finally {
					captcha.clear();
				}
			}
		};
	}

	public void renderFeedbackPanel(Form<User> form) {
		FeedbackPanel feedbackPanel = new FeedbackPanel("feedback");
		feedbackPanel.setFilter(new ErrorLevelsFeedbackMessageFilter(FeedbackMessage.ERROR));
		form.add(feedbackPanel);
	}

	public void renderTitleLabel() {
		add(new Label("title", getTitleModel()));
		add(new Label("titlelabel", getTitleModel()));
	}

	protected IModel<String> getTitleModel() {
		IModel<String> titleModel = new Model<String>("电信群发营销管理系统");

		try {
			titleModel.setObject(systemConfigService.getSystemConfigByKey(SystemConfigConstants.SYSTEM_TITLE).getConfigValue());
		} catch (ServiceException e) {
			logger.error(e.getMessage());
		}

		return titleModel;
	}

	public void renderUserAccountTextField(Form<User> form) {
		TextField<String> txtAccount = new TextField<String>("txtAccount", new PropertyModel<String>(form.getDefaultModelObject(), "account"));
		txtAccount.setRequired(true);
		txtAccount.setOutputMarkupId(true);
		txtAccount.setMarkupId("txtAccount");
		txtAccount.add(new ComponentVisualErrorBehavior());
		form.add(txtAccount);
	}

	public void renderUserPasswordTextField(Form<User> form) {
		PasswordTextField txtPassword = new PasswordTextField("txtPassword", new PropertyModel<String>(form.getDefaultModelObject(), "password"));
		txtPassword.setRequired(true);
		txtPassword.setOutputMarkupId(true);
		txtPassword.setResetPassword(false);
		txtPassword.setMarkupId("txtPassword");
		txtPassword.add(new ComponentVisualErrorBehavior());
		form.add(txtPassword);
	}

	public void renderCaptchaTextField(Form<User> form, Captcha captcha) {
		TextField<String> txtCaptcha = new TextField<String>("txtCaptcha", new PropertyModel<String>(captcha, "actual"));
		txtCaptcha.setRequired(true);
		txtCaptcha.setOutputMarkupId(true);
		txtCaptcha.setMarkupId("txtCaptcha");
		txtCaptcha.add(new ComponentVisualErrorBehavior());
		form.add(txtCaptcha);
		form.add(new NonCachingImage("imgCaptcha", new CaptchaImageResource(captcha)));
	}

	public void renderLoginLink(final Form<User> form) {
		form.add(new SubmitLink("loginLink"));
	}
}
